<template>
  <div class="main1">
    <div style="margin: 10px">
      <span>用户权限管理：</span>
      <Select
        v-model="selectedRole"
        style="width: 300px"
        @on-change="changeTaskInfo"
      >
        <Option
          v-for="(item, index) in classTaskList"
          :value="item.value"
          :key="index"
          >{{ item.label }}</Option
        >
      </Select>
      <span style="float: right; text-align: center; line-height: 35px"
        >共包含用户<span style="color: blue; font-size: 900; margin: 0 3px">{{
          homeworkList.length
        }}</span
        >人</span
      >
      <Button
        id="addUser"
        type="primary"
        @click="addUserModalShow()"
        style="margin-letf: 10px; z-index: 1; position: relative"
        >添加账号</Button
      >
    </div>
    <Table
      border
      :height="contentPageCSS - 145"
      :columns="columns5"
      :data="homeworkList"
    >
      <template #action="{ index }">
        <Button
          type="primary"
          size="small"
          style="margin-right: 10px"
          @click="resetPwd(index)"
          v-if="homeworkList[index].userId != 'admin'"
          >重置密码</Button
        ><Button
          type="warning"
          size="small"
          style="margin-right: 10px"
          @click="changeRole(index)"
          v-if="homeworkList[index].userId != 'admin'"
          >修改权限</Button
        >
        <Button
          type="error"
          size="small"
          @click="removeUser(index)"
          v-if="homeworkList[index].userId != 'admin'"
          >删除账号</Button
        >
      </template></Table
    >
    <Modal v-model="addUserModal" title="添加用户" @on-ok="commitAdd">
      用户名：
      <Input
        v-model="newUserName"
        type="text"
        password
        placeholder="请输入用户名"
        style="width: 200px"
      />
      <br /><br />
      用户账号：
      <Input
        v-model="newUserId"
        type="text"
        password
        placeholder="请输入账号"
        style="width: 200px"
      />
      <br /><br />
      设置用户权限：
      <RadioGroup v-model="newUserRole" type="button">
        <Radio label="student">学生</Radio>
        <Radio label="teacher">老师</Radio>
        <Radio label="admin">管理员</Radio>
      </RadioGroup>
      <br /><br />
      新密码：
      <Input
        v-model="newPwd"
        type="password"
        password
        placeholder="请输入新密码"
        style="width: 200px"
      />
      <br /><br />
      确认密码：
      <Input
        v-model="newPwd2"
        type="password"
        password
        placeholder="请输入新密码"
        style="width: 200px"
      />
      <br /><br />
      <h2 style="margin-bottom: 20px">
        系统默认密码为
        <span style="color: blue">T123456</span> ，您可以点击<a
          @click="clearNewPwd"
          >清空</a
        >重新设置。
      </h2>
    </Modal>
    <Modal v-model="resetPwdModal" title="重置密码" @on-ok="commitReset">
      <h2
        v-if="
          selectedUserInfo.name != undefined &&
          selectedUserInfo.userId != 'admin'
        "
        style="margin-bottom: 20px"
      >
        您正在重置该用户
        <span style="color: blue">
          {{ selectedUserInfo.name }} ({{ selectedUserInfo.userId }})
        </span>
        的密码！
      </h2>
      <h2 style="margin-bottom: 20px">
        系统默认重置密码为
        <span style="color: blue" v-if="selectedUserInfo.role == 'student'"
          >s123456</span
        >
        <span style="color: blue" v-else>T123456</span> ，您可以点击<a
          @click="clearNewPwd"
          >清空</a
        >重新设置。
      </h2>
      新密码：
      <Input
        v-model="newPwd"
        type="password"
        password
        placeholder="请输入新密码"
        style="width: 200px"
      />
      <br /><br />
      确认密码：
      <Input
        v-model="newPwd2"
        type="password"
        password
        placeholder="请输入新密码"
        style="width: 200px"
      />
    </Modal>
    <Modal v-model="changeRoleModal" title="修改权限" @on-ok="commitChange">
      <h2
        v-if="
          selectedUserInfo.name != undefined &&
          selectedUserInfo.userId != 'admin'
        "
        style="margin-bottom: 20px"
      >
        您正在修改该用户
        <span style="color: blue">
          {{ selectedUserInfo.name }} ({{ selectedUserInfo.userId }})
        </span>
        的用户权限！
      </h2>
      设置用户权限：
      <RadioGroup v-model="userRole" type="button">
        <Radio label="student">学生</Radio>
        <Radio label="teacher">老师</Radio>
        <Radio label="admin">管理员</Radio>
      </RadioGroup>
    </Modal>
    <Modal v-model="deleteUserModal" title="删除账号" @on-ok="commitDelete">
      <h2
        v-if="
          selectedUserInfo.name != undefined &&
          selectedUserInfo.userId != 'admin'
        "
        style="margin-bottom: 20px"
      >
        您确认要删除该用户
        <span style="color: blue">
          {{ selectedUserInfo.name }} ({{ selectedUserInfo.userId }})
        </span>
        吗！
      </h2>
    </Modal>
  </div>
</template>

<script>
import md5 from "js-md5";
import { get, post, del, put } from "@/axios";
export default {
  props: ["contentPageCSS"],
  data() {
    return {
      scrollOps: {
        bar: {
          background: "#808695",
        },
      },
      columns5: [
        {
          title: "姓名",
          key: "name",
        },
        {
          title: "账号",
          key: "userId",
        },
        // {
        //   title: "创建日期",
        //   key: "createTime",
        //   sortable: true,
        // },

        {
          title: "身份",
          key: "role",
          sortable: true,
        },
        {
          title: "管理",
          slot: "action",
          key: "scoreReview",
        },
      ],
      userInfo: {},
      selectedRole: "All",
      classTaskList: [
        {
          value: "All",
          label: "All",
        },
        {
          value: "student",
          label: "Student",
        },
        {
          value: "teacher",
          label: "Teacher",
        },
        {
          value: "admin",
          label: "Admin",
        },
      ],
      homeworkList: [],
      classId: "",
      selectedUserInfo: {},
      addUserModal: false,
      resetPwdModal: false,
      changeRoleModal: false,
      deleteUserModal: false,
      newUserName: "",
      newUserId: "",
      newUserRole: "teacher",
      newPwd: "s123456",
      newPwd2: "s123456",
      userRole: "student",
      selectedIndex: -1,
    };
  },
  created() {},
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.getUserListByRole("All");
  },
  methods: {
    async getUserListByRole(value) {
      try {
        let res = await get(
          "/visualResourceLibrary/user/getUsersByRole/" + value
        );
        let list = res.data.data;
        this.selectedRole = value;
        this.homeworkList = list;
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    addUserModalShow() {
      this.newUserName = "";
      this.newUserId = "";
      this.newUserRole = "teacher";
      this.newPwd = "T123456";
      this.newPwd2 = "T123456";
      this.addUserModal = true;
    },
    async commitAdd() {
      if (this.newPwd == this.newPwd2) {
        if (this.newUserName != "" && this.newUserId != "") {
          try {
            var userData = {
              name: this.newUserName,
              userId: this.newUserId,
              role: this.newUserRole,
              password: md5(this.newPwd2),
            };
            let res = await post("/visualResourceLibrary/user", userData)
              .then((res) => {
                if (res.data.code == -3) {
                  this.$Message.error("该学号已被注册!");
                  this.registerForm.email = "";
                } else if (res.data.code == 0) {
                  this.$Message.success("注册成功");
                  this.$router.replace({ name: "Login" });
                }
              })
              .catch((err) => {
                throw err;
              });
          } catch (e) {
            this.$Message.error("操作失败");
            console.log(e);
          }
        } else {
          this.$Message.error("请输入用户名或账号！");
        }
      } else {
        this.$Message.error("两次密码不一致，请重试！");
      }
    },
    changeTaskInfo(value) {
      console.log(value);
      this.getUserListByRole(value);
    },
    resetPwd(index) {
      this.selectedUserInfo = this.homeworkList[index];
      if (this.selectedUserInfo.role == "student") {
        this.newPwd = "s123456";
        this.newPwd2 = "s123456";
      } else {
        this.newPwd = "T123456";
        this.newPwd2 = "T123456";
      }
      this.resetPwdModal = true;
    },
    async commitReset() {
      if (this.newPwd == this.newPwd2) {
        try {
          let res = await get(
            "/visualResourceLibrary/user/resetPwd/" +
              this.selectedUserInfo.userId +
              "/" +
              md5(this.newPwd)
          );
          this.$Message.success("修改成功！");
        } catch (e) {
          this.$Message.error("修改失败");
          console.log(e);
        }
      } else {
        this.$Message.error("两次密码不一致，请重试！");
      }
    },
    changeRole(index) {
      this.changeRoleModal = true;
      this.selectedUserInfo = this.homeworkList[index];
      this.userRole = this.selectedUserInfo.role;
      this.selectedIndex = index;
    },
    async commitChange() {
      try {
        let res = await get(
          "/visualResourceLibrary/user/changeUserRole/" +
            this.selectedUserInfo.userId +
            "/" +
            this.userRole
        );
        this.homeworkList[this.selectedIndex].role = this.userRole;
        this.$Message.success("修改成功！");
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    removeUser(index) {
      this.deleteUserModal = true;
      this.selectedUserInfo = this.homeworkList[index];
      this.selectedIndex = index;
    },
    async commitDelete() {
      try {
        let res = await get(
          "/visualResourceLibrary/user/delete/" + this.selectedUserInfo.userId
        );
        this.homeworkList.splice(this.selectedIndex, 1);
        this.$Message.success("修改成功！");
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    clearNewPwd() {
      this.newPwd = "";
      this.newPwd2 = "";
    },
  },
};
</script>

<style>
</style>